package in.wenwen.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import in.wenwen.entity.User;
import in.wenwen.handler.AdminHandler;
import in.wenwen.service.IUserService;
import in.wenwen.util.ConstUtil;
import in.wenwen.util.MD5Util;
import in.wenwen.util.UserManage;

import org.jiucheng.ioc.annotation.Inject;
import org.jiucheng.util.StringUtil;
import org.jiucheng.web.annotation.Controller;
import org.jiucheng.web.annotation.RequestMapping;
import org.jiucheng.web.annotation.Param;
import org.jiucheng.web.annotation.RequestMethod;

@Controller(AdminHandler.class)
public class AdminMeController {

    @Inject
    private IUserService userService;

    @RequestMapping(value = "/admin/me/edit.html", method = RequestMethod.GET)
    public String edit() {
        return ConstUtil.getAdminUri("me/edit");
    }

    @RequestMapping(value = "/admin/me/edit.html", method = RequestMethod.POST)
    public String editPost(@Param("ypassword") String ypassword,
            @Param("xpassword") String xpassword, HttpServletRequest request) {
        String rs = ConstUtil.getAdminUri("me/edit");
        if (StringUtil.isBlank(xpassword) || StringUtil.isBlank(ypassword)) {
            request.setAttribute(ConstUtil.ERR, "*密码不能为空");
            return rs;
        }
        User user = userService.get(User.class, UserManage.getWebappDto().getUser().getId());
        if (user == null) {
            request.setAttribute(ConstUtil.ERR, "*账号已不存在");
            return rs;
        }
        if (!MD5Util.getMd5(ypassword).equals(user.getPassword())) {
            request.setAttribute(ConstUtil.ERR, "*原密码错误");
            return rs;
        }
        user = new User();
        user.setId(UserManage.getUserDto().getId());
        user.setModifyDatetime(new Date());
        user.setPassword(MD5Util.getMd5(xpassword));
        userService.update(user);
        request.setAttribute(ConstUtil.ERR, "*修改成功");
        return rs;
    }

    @RequestMapping(value = "/admin/me/nick/edit.html", method = RequestMethod.GET)
    public String nickEdit(HttpServletRequest request) {
        request.setAttribute("nick", UserManage.getUserNick());
        return ConstUtil.getAdminUri("me/nick/edit");
    }

    @RequestMapping(value = "/admin/me/nick/edit.html", method = RequestMethod.POST)
    public String nickEditPost(@Param("nick") String nick, HttpServletRequest request) {
        if (StringUtil.isNotBlank(nick)) {
            User user = new User();
            user.setId(UserManage.getUserDto().getId());
            user.setNick(nick.trim());
            user.setModifyDatetime(UserManage.getReceiveDatetime());
            userService.update(user);
        }
        return ConstUtil.getAdminUri("me/nick/edit-success");
    }
}
